package com.woniu.common.token;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.common.constant.Constants;
import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenServiceUtil {


    @Value("${woniu.tokenSecret}")
    private String tokenSecret;

    public String generateToken(Long userId,String userName,String userAccount){

        AccToken accToken = new AccToken(userId, userName, userAccount, new Date(new Date().getTime() + (3600 * 1000 * 24 * 30L)));
        ObjectMapper mapper = new ObjectMapper();
        try {
            String accTokenJson = mapper.writeValueAsString(accToken);
            Map<String,Object> claims = new HashMap<>();
            claims.put(Constants.LOGIN_USER_KEY,accTokenJson);

            JwtBuilder builder = Jwts.builder();
            builder.setClaims(claims);
            builder.signWith(SignatureAlgorithm.HS512, tokenSecret);
            String jwtToken = builder.compact();

            return jwtToken;

        } catch (JsonProcessingException e) {
            throw new CustomException(ExceptionCode.JSON_CONVERTION);
        }


    }


    private Claims parseToken(String token){
        return Jwts.parser().setSigningKey(tokenSecret).parseClaimsJws(token).getBody();
    }

    public AccToken getAccToken(String token){
        Claims claims = parseToken(token);

        //从map中获取json字符串
        String accTokenJson = (String)claims.get(Constants.LOGIN_USER_KEY);

        ObjectMapper mapper = new ObjectMapper();

//        把json转成对象

        AccToken accToken = null;
        try {
            accToken = mapper.readValue(accTokenJson, AccToken.class);
            return accToken;
        } catch (JsonProcessingException e) {
            throw new CustomException(ExceptionCode.JSON_CONVERTION);
        }

    }

    public static void main(String[] args) {
        System.out.println(3600*1000*24*30L);
    }
}
